var orm = require("orm");
// var connections = {};
const path = require("path");
const modelsPath = path.join(process.cwd(), "/models");
const fs = require("fs");

function initialize(app, callback) {
//   if (connections["host"] && connections["host"]["database"]) {
//     return connections["host"]["database"];
//   }
  const config = require("config").get("db_config");

  const opts = {
    host: config.get("host"),
    database: config.get("database"),
    protocol: config.get("protocol"),
    port: config.get("port"),
    user: config.get("user"),
    password: config.get("password"),
    query: { pool: true, debug: true },
  };

  orm.connect(opts, function (err, db) {
    if (err) return callback(err);

    // app.db = db;
    //挂载到全局
    global.database = db;

    //加载 models 到db
    fs.readdir(modelsPath, function (err, files) {
      // let loadModelAsynFns = new Array();
      for (const file of files) {
        const modelPath = modelsPath + "/" + file;
        db.loadAsync(modelPath);
        // loadModelAsynFns.push(db.loadAsync(modelPath));
      }
      // Promise.all(loadModelAsynFns).then(function() {
      // })
    });

    // connections["host"] = connections["host"] || {};
    // connections["host"]["database"] = db;
  });
}

// initialize();

module.exports.initialize = initialize;
// module.exports.getDatabase = function() {
//     return global.database;
// }
